#!/usr/bin/env python3
"""
ITS系统用户初始化脚本
用于创建各个角色的测试账号
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from sqlalchemy.orm import Session
from app.database import SessionLocal, engine
from app.models.user import User
from app.crud.user import create_user, get_user_by_email
from app.schemas.user import UserCreate
from passlib.context import CryptContext

# 密码加密上下文
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def get_password_hash(password):
    return pwd_context.hash(password)

def init_test_users():
    """初始化测试用户"""
    db = SessionLocal()
    
    try:
        # 测试用户数据 - 密码统一为 123456
        test_users = [
            # 管理员账号
            {
                "username": "admin",
                "email": "admin@example.com", 
                "password": "123456",
                "role": "admin",
                "description": "系统管理员 - 拥有所有权限"
            },
            {
                "username": "system_admin",
                "email": "admin@test.com",
                "password": "123456", 
                "role": "admin",
                "description": "系统管理员 - 测试账号"
            },
            
            # 工程师账号
            {
                "username": "engineer_zhang",
                "email": "zhang@test.com",
                "password": "123456",
                "role": "engineer", 
                "description": "高级工程师 - 张工"
            },
            {
                "username": "engineer_li",
                "email": "li@test.com",
                "password": "123456",
                "role": "engineer",
                "description": "工程师 - 李工" 
            },
            {
                "username": "senior_engineer",
                "email": "senior@test.com",
                "password": "123456",
                "role": "engineer",
                "description": "资深工程师 - 问题处理专家"
            },
            
            # 客户账号
            {
                "username": "customer_wang",
                "email": "wang@test.com", 
                "password": "123456",
                "role": "customer",
                "description": "普通客户 - 王先生"
            },
            {
                "username": "customer_liu",
                "email": "liu@test.com",
                "password": "123456", 
                "role": "customer",
                "description": "普通客户 - 刘女士"
            },
            {
                "username": "vip_customer", 
                "email": "vip@test.com",
                "password": "123456",
                "role": "customer",
                "description": "VIP客户 - 重要客户"
            }
        ]
        
        created_count = 0
        skipped_count = 0
        
        print("开始创建测试用户...")
        print("=" * 60)
        
        for user_data in test_users:
            # 检查用户是否已存在
            existing_user = get_user_by_email(db, user_data["email"])
            if existing_user:
                print(f"跳过: {user_data['username']} ({user_data['email']}) - 用户已存在")
                skipped_count += 1
                continue
            
            # 创建新用户
            try:
                user_create = UserCreate(
                    username=user_data["username"],
                    email=user_data["email"],
                    password=user_data["password"],
                    role=user_data["role"]
                )
                
                new_user = create_user(db, user_create)
                print(f"创建: {new_user.username} ({new_user.email}) - {user_data['description']}")
                created_count += 1
                
            except Exception as e:
                print(f"错误: 创建用户 {user_data['username']} 失败 - {str(e)}")
        
        print("=" * 60)
        print(f"用户创建完成: 新建 {created_count} 个，跳过 {skipped_count} 个")
        
        # 显示所有用户账号信息
        print("\n" + "=" * 60)
        print("测试账号信息:")
        print("=" * 60)
        print("角色         | 用户名           | 邮箱              | 密码")
        print("-" * 60)
        
        for user_data in test_users:
            role_name = {"admin": "管理员", "engineer": "工程师", "customer": "客户"}[user_data["role"]]
            print(f"{role_name:<8} | {user_data['username']:<15} | {user_data['email']:<16} | 123456")
        
        print("\n访问地址:")
        print("- 系统首页: http://localhost:8080")
        print("- API文档: http://localhost:8001/docs")
        
    except Exception as e:
        print(f"初始化过程中发生错误: {str(e)}")
        db.rollback()
    finally:
        db.close()

if __name__ == "__main__":
    print("ITS系统用户初始化脚本")
    print("=" * 60)
    
    try:
        # 确保数据库表已创建
        from app.models import user, case, issue, attachment, setting
        from app.database import Base
        Base.metadata.create_all(bind=engine)
        
        # 初始化用户
        init_test_users()
        
    except Exception as e:
        print(f"脚本执行失败: {str(e)}")
        sys.exit(1)
    
    print("\n脚本执行完成!")